<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        form {
            margin-bottom: 20px;
        }
        input {
            margin-right: 10px;
            padding: 5px;
        }
        button {
            padding: 5px 10px;
            cursor: pointer;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
        }
    </style>
</head>
<body>
<h1>User Management</h1>

<!-- Create User Form -->
<h2>Create User</h2>
<form id="createUserForm">
    <input type="text" id="username" placeholder="Username" required>
    <input type="password" id="password" placeholder="Password" required>
    <input type="email" id="email" placeholder="Email" required>
    <button type="submit">Create User</button>
</form>

<!-- Search User by Username -->
<h2>Search User by Username</h2>
<form id="searchUserForm">
    <input type="text" id="searchUsername" placeholder="Username" required>
    <button type="submit">Search</button>
</form>
<div id="searchResult"></div>

<!-- User List -->
<h2>All Users</h2>
<button onclick="fetchAllUsers()">Refresh User List</button>
<table>
    <thead>
    <tr>
        <th>ID</th>
        <th>Username</th>
        <th>Email</th>
        <th>Created At</th>
        <th>Actions</th>
    </tr>
    </thead>
    <tbody id="userTableBody">
    <!-- User rows will be dynamically added here -->
    </tbody>
</table>

<script>
    const API_BASE_URL = 'http://localhost:8080/user2'; // 后端 API 的基础 URL

    // 创建用户s
    document.getElementById('createUserForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const email = document.getElementById('email').value;

        try {
            const response = await axios.post(API_BASE_URL, { username, password, email });
            alert('User created successfully!');
            document.getElementById('createUserForm').reset();
            fetchAllUsers(); // 刷新用户列表
        } catch (error) {
            console.error(error);
            alert('Failed to create user. Please check the console for details.');
        }
    });

    // 搜索用户
    document.getElementById('searchUserForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const username = document.getElementById('searchUsername').value;

        try {

            const response = await axios.get(`${API_BASE_URL}/search`, { params: { id:username,t:new Date().getTime() } });
            const user = response.data;
            if (user) {
                document.getElementById('searchResult').innerHTML = `
            <p><strong>ID:</strong> ${user.id}</p>
            <p><strong>Username:</strong> ${user.username}</p>
            <p><strong>Email:</strong> ${user.email}</p>
            <p><strong>Created At:</strong> ${user.createdAt}</p>
          `;
            } else {
                document.getElementById('searchResult').innerHTML = '<p>User not found.</p>';
            }
        } catch (error) {
            console.error(error);
            alert('Failed to search user. Please check the console for details.');
        }
    });

    // 获取所有用户
    async function fetchAllUsers() {
        try {
            const response = await axios.get(API_BASE_URL);
            const users = response.data;
            const userTableBody = document.getElementById('userTableBody');
            userTableBody.innerHTML = ''; // 清空表格内容

            users.forEach(user => {
                const row = document.createElement('tr');
                row.innerHTML = `
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>${user.email}</td>
            <td>${user.createdAt}</td>
            <td>
              <button onclick="deleteUser(${user.id})">Delete</button>
            </td>
          `;
                userTableBody.appendChild(row);
            });
        } catch (error) {
            console.error(error);
            alert('Failed to fetch users. Please check the console for details.');
        }
    }

    // 删除用户
    async function deleteUser(id) {
        debugger;
        if (!confirm('Are you sure you want to delete this user?')) return;

        try {
            await axios.delete(`${API_BASE_URL}/${id}`);
            alert('User deleted successfully!');
            fetchAllUsers(); // 刷新用户列表
        } catch (error) {
            console.error(error);
            alert('Failed to delete user. Please check the console for details.');
        }
    }

    // 初始化加载所有用户
    fetchAllUsers();
</script>
</body>
</html>
